<template>
  <div class="permission-demo">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>权限管理演示</h2>
          <el-button type="primary" @click="refreshPermissions">
            <el-icon><Refresh /></el-icon>
            刷新权限
          </el-button>
        </div>
      </template>

      <!-- 当前用户信息 -->
      <div class="user-info">
        <h3>当前用户信息</h3>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="用户名">{{ userInfo.username }}</el-descriptions-item>
          <el-descriptions-item label="姓名">{{ userInfo.name }}</el-descriptions-item>
          <el-descriptions-item label="角色">{{ userInfo.role }}</el-descriptions-item>
          <el-descriptions-item label="权限数量">{{ userInfo.permissions?.length || 0 }}</el-descriptions-item>
          <el-descriptions-item label="最后检查">{{ lastCheckTime }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="isOnline ? 'success' : 'warning'">
              {{ isOnline ? '在线' : '离线' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 权限列表 -->
      <div class="permissions-list">
        <h3>当前权限列表</h3>
        <el-tag 
          v-for="permission in userInfo.permissions" 
          :key="permission"
          class="permission-tag"
          type="info"
        >
          {{ permission }}
        </el-tag>
      </div>

      <!-- 权限控制演示 -->
      <div class="permission-demo-section">
        <h3>权限控制演示</h3>
        
        <!-- 基于权限的控制 -->
        <div class="demo-group">
          <h4>基于权限的控制</h4>
          <div class="demo-items">
            <el-button v-permission="'user_manage'" type="primary">
              用户管理（需要 user_manage 权限）
            </el-button>
            <el-button v-permission="'system_config'" type="success">
              系统配置（需要 system_config 权限）
            </el-button>
            <el-button v-permission="'data_analysis'" type="warning">
              数据分析（需要 data_analysis 权限）
            </el-button>
            <el-button v-permission="'log_audit'" type="danger">
              日志审计（需要 log_audit 权限）
            </el-button>
          </div>
        </div>

        <!-- 基于角色的控制 -->
        <div class="demo-group">
          <h4>基于角色的控制</h4>
          <div class="demo-items">
            <el-button v-role="'ADMIN'" type="primary">
              管理员功能（需要 ADMIN 角色）
            </el-button>
            <el-button v-role="'TEACHER'" type="success">
              教师功能（需要 TEACHER 角色）
            </el-button>
            <el-button v-role="'STUDENT'" type="warning">
              学生功能（需要 STUDENT 角色）
            </el-button>
            <el-button v-role="['ADMIN', 'TEACHER']" type="info">
              管理员或教师功能
            </el-button>
          </div>
        </div>

        <!-- 权限或角色控制 -->
        <div class="demo-group">
          <h4>权限或角色控制</h4>
          <div class="demo-items">
            <el-button v-permission.or="['user_manage', 'ADMIN']" type="primary">
              用户管理或管理员
            </el-button>
            <el-button v-permission.or="['system_config', 'ADMIN']" type="success">
              系统配置或管理员
            </el-button>
          </div>
        </div>

        <!-- 权限检查工具 -->
        <div class="demo-group">
          <h4>权限检查工具</h4>
          <div class="demo-items">
            <el-button @click="checkPermission('user_manage')" type="primary">
              检查 user_manage 权限
            </el-button>
            <el-button @click="checkRole('ADMIN')" type="success">
              检查 ADMIN 角色
            </el-button>
            <el-button @click="checkPermissionOrRole('user_manage', 'ADMIN')" type="warning">
              检查权限或角色
            </el-button>
          </div>
        </div>
      </div>

      <!-- 权限变更日志 -->
      <div class="permission-logs">
        <h3>权限变更日志</h3>
        <el-timeline>
          <el-timeline-item
            v-for="log in permissionLogs"
            :key="log.id"
            :timestamp="log.time"
            :type="log.type"
          >
            {{ log.message }}
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { 
  hasPermission, 
  hasRole, 
  hasPermissionOrRole, 
  refreshUserPermissions 
} from '@/utils/permission'

export default {
  name: 'PermissionDemo',
  setup() {
    const store = useStore()
    const isOnline = ref(true)
    const permissionLogs = ref([])

    const userInfo = computed(() => {
      const user = store.state.user.userInfo || store.state.user
      return {
        username: user.username,
        name: user.name,
        role: user.role,
        permissions: user.permissions || []
      }
    })

    const lastCheckTime = computed(() => {
      const user = store.state.user.userInfo || store.state.user
      const timestamp = user.lastPermissionCheck
      return timestamp ? new Date(timestamp).toLocaleString() : '从未检查'
    })

    const addLog = (message, type = 'primary') => {
      permissionLogs.value.unshift({
        id: Date.now(),
        time: new Date().toLocaleString(),
        message,
        type
      })
      // 只保留最近10条日志
      if (permissionLogs.value.length > 10) {
        permissionLogs.value = permissionLogs.value.slice(0, 10)
      }
    }

    const refreshPermissions = async () => {
      try {
        await refreshUserPermissions()
        addLog('权限刷新成功', 'success')
        ElMessage.success('权限已刷新')
      } catch (error) {
        addLog('权限刷新失败: ' + error.message, 'danger')
        ElMessage.error('权限刷新失败')
      }
    }

    const checkPermission = (permission) => {
      const has = hasPermission(permission)
      const message = has ? `有 ${permission} 权限` : `没有 ${permission} 权限`
      addLog(message, has ? 'success' : 'warning')
      ElMessage.info(message)
    }

    const checkRole = (role) => {
      const has = hasRole(role)
      const message = has ? `有 ${role} 角色` : `没有 ${role} 角色`
      addLog(message, has ? 'success' : 'warning')
      ElMessage.info(message)
    }

    const checkPermissionOrRole = (permission, role) => {
      const has = hasPermissionOrRole(permission, role)
      const message = has ? `有 ${permission} 权限或 ${role} 角色` : `没有 ${permission} 权限或 ${role} 角色`
      addLog(message, has ? 'success' : 'warning')
      ElMessage.info(message)
    }

    onMounted(() => {
      addLog('页面加载完成')
    })

    return {
      userInfo,
      lastCheckTime,
      isOnline,
      permissionLogs,
      refreshPermissions,
      checkPermission,
      checkRole,
      checkPermissionOrRole
    }
  }
}
</script>

<style scoped>
.permission-demo {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  color: var(--text-color);
}

.user-info {
  margin-bottom: 30px;
}

.user-info h3 {
  margin-bottom: 16px;
  color: var(--text-color);
}

.permissions-list {
  margin-bottom: 30px;
}

.permissions-list h3 {
  margin-bottom: 16px;
  color: var(--text-color);
}

.permission-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

.permission-demo-section {
  margin-bottom: 30px;
}

.permission-demo-section h3 {
  margin-bottom: 20px;
  color: var(--text-color);
}

.demo-group {
  margin-bottom: 24px;
}

.demo-group h4 {
  margin-bottom: 12px;
  color: var(--text-color-secondary);
  font-size: 14px;
}

.demo-items {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.permission-logs h3 {
  margin-bottom: 16px;
  color: var(--text-color);
}
</style> 